namespace SimpleWebServices.Configuration
{
    using System;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Globalization;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    using SimpleWebServices.Web.UI.Html;

    [XmlRoot("elements")]
    public sealed class HtmlElementCollection : Collection<IElementSerializable>, IXmlSerializable
    {
        XmlSchema IXmlSerializable.GetSchema()
        {
            throw new NotSupportedException();
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsEmptyElement)
            {
                reader.Read();
            }
            else
            {
                string name = reader.Name;
                while (true)
                {
                    if (XmlNodeType.EndElement == reader.NodeType && reader.Name == name)
                    {
                        reader.Read();
                        break;
                    }
                    else if ("element".Equals(reader.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        Type type = Type.GetType(reader.GetAttribute("type"), true);

                        this.Add((IElementSerializable)Activator.CreateInstance(type));
                    }

                    reader.Read();
                }
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            if (null == writer)
            {
                throw new ArgumentNullException("writer");
            }

            foreach (IElementSerializable element in this)
            {
                writer.WriteRaw(string.Format(CultureInfo.InvariantCulture, "<element type='{0}, {1}' />", element.GetType().FullName, element.GetType().Assembly.GetName().Name));
            }
        }
    }
}